<template>
  <el-dialog
    v-model="dialogVisible"
    title="导入 Mermaid"
    width="50%"
    :before-close="handleClose"
  >
    <el-input
      v-model="mermaidText"
      type="textarea"
      :rows="10"
      placeholder="请输入 Mermaid 格式的思维导图文本，例如：
mindmap
  根节点
    子节点1
      子节点1.1
    子节点2
      子节点2.1
      子节点2.2"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { mermaidToMindMap } from '../../utils/mermaidParser.ts'

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', data: any): void
}>()

const dialogVisible = ref(props.modelValue)
const mermaidText = ref('')

watch(() => props.modelValue, (newValue) => {
  dialogVisible.value = newValue
})

watch(() => dialogVisible.value, (newValue) => {
  emit('update:modelValue', newValue)
})

const handleClose = () => {
  dialogVisible.value = false
  mermaidText.value = ''
}

const handleConfirm = () => {
  try {
    if (!mermaidText.value.trim()) {
      ElMessage.warning('请输入 Mermaid 格式的文本')
      return
    }
    const data = mermaidToMindMap(mermaidText.value)
    emit('confirm', data)
    handleClose()
  } catch (error) {
    ElMessage.error('解析失败：请检查输入格式是否正确')
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}
</style>